import { Injectable } from '@nestjs/common';
import { UserWalletLog } from 'src/entities/UserWalletLog';
import { Connection } from 'typeorm';

@Injectable()
export class ChargeService {
    constructor(
        private connection: Connection
    ){}

    async startTransaction() {
        const queryRunner = this.connection.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction()

        return queryRunner
    }

    walletUpdate(amount, rechargeBalance, rewardBalance, order, wallet) {
        let walletUpdate:{amount? : string, rewardAmount? : string} = {}
        let walletLog:{[key in keyof UserWalletLog]? : UserWalletLog[key]} = {
            userId : order.userId,
            beforeAmount : wallet.amount,
            beforeRewardAmount : wallet.rewardAmount
        }

        if(rechargeBalance >= amount) { //充值余额够钱
            order.feeAmount = order.chargeAmount //充电订单中充值余额支出部分
            walletUpdate.amount = String(rechargeBalance - amount) //钱包充值余额，更新钱包
            

            walletLog.amount = String(-amount) //余额部分支付的
            //支出之后钱包的余额记录
            walletLog.afterAmount = walletUpdate.amount
            walletLog.afterRewardAmount = wallet.rewardAmount //赠送余额不变
        }else {
            let offset = amount - rechargeBalance
            
            order.feeRewardAmount = String(offset) //充电订单中赠送余额支出部分
            walletUpdate.rewardAmount = String(rewardBalance - offset) //钱包赠送余额，更新钱包
            
            walletLog.rewardAmount = String(-offset)  //赠送余额支出部分

            //支出之后钱包的赠送余额记录
            walletLog.afterRewardAmount = walletUpdate.rewardAmount

            if(rechargeBalance > 0) { //如果充值余额有钱的
                order.feeAmount = String(rechargeBalance) //充值余额全部给出
                walletUpdate.amount = '0' //钱包充值余额，更新钱包

                walletLog.amount = String(-rechargeBalance)
                walletLog.afterAmount = walletUpdate.amount
            }

        }

        return {
            walletLog,
            walletUpdate
        }
    }

}
